import { ref, computed } from 'vue'

export default (m1 = 0, m2 = 5, s1 = 0, s2 = 0) => {
  const MAX_MINUTE2 = 9
  const MAX_SECOND1 = 5
  const MAX_SECOND2 = 9

  const INTERVAL = 1000
  const minute1 = ref(m1)
  const minute2 = ref(m2)
  const second1 = ref(s1)
  const second2 = ref(s2)
  const timerID: any = ref(null)

  const isTimeOut = computed(
    () => !minute1.value && !minute2.value && !second1.value && !second2.value
  )

  const getImageURL = (url: string) => {
    return new URL(`./images/nums/num_${url}.png`, import.meta.url).href
  }

  const initMinute1 = () => {
    if (!minute1.value) {
      return
    }

    minute1.value--
  }

  const initMinute2 = () => {
    if (!minute2.value) {
      minute2.value += MAX_MINUTE2
      initMinute1()
      return
    }

    minute2.value--
  }

  const initSecond1 = () => {
    if (!second1.value) {
      second1.value += MAX_SECOND1
      initMinute2()
      return
    }
    second1.value--
  }

  const startCountDown = () => {
    return new Promise((resolve) => {
      timerID.value = setInterval(() => {
        if (!second2.value) {
          if (!isTimeOut.value) {
            second2.value += MAX_SECOND2
            initSecond1()
            return
          }
          clearInterval(timerID)

          resolve('timeout')
          return
        }
        second2.value--
      }, INTERVAL)
    })
  }

  const start = async () => {
    startCountDown()
  }

  const resetCountDown = () => {
    clearInterval(timerID)
    minute2.value = 5
    second1.value = 0
    second2.value = 0
    timerID.value = null
  }

  return {
    minute1,
    minute2,
    second1,
    second2,
    resetCountDown,
    start,
    getImageURL,
  }
}
